/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.yczbj.ycvideoplayer.fraction;

import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.components.TableLayoutManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import com.yc.video.config.VideoInfoBean;

import org.yczbj.ycvideoplayer.ConstantVideo;
import org.yczbj.ycvideoplayer.ResourceTable;
import org.yczbj.ycvideoplayer.adapter.TikTokListAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Recyclerview Video
 *
 * @since 2021-05-10
 */
public class TikTokListFragment extends BaseFraction {
    protected ListContainer mListContainer;
    private TikTokListAdapter mAdapter;
    private List<VideoInfoBean> data = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return ResourceTable.Layout_base_recycler_view;
    }

    @Override
    protected void initComponent(Component rootComponent, Intent intent) {
        super.initComponent(mRootComponent, intent);
        mListContainer = (ListContainer) rootComponent.findComponentById(ResourceTable.Id_recyclerView);
        TableLayoutManager tableLayoutManager = new TableLayoutManager();
        tableLayoutManager.setColumnCount(2);
        mListContainer.setLayoutManager(tableLayoutManager);
        mAdapter = new TikTokListAdapter(getFractionAbility());
        mListContainer.setItemProvider(mAdapter);
        initData();
    }

    private void initData() {
        // 模拟请求数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<VideoInfoBean> tiktokBeans = ConstantVideo.getVideoList();
                data.clear();
                data.addAll(tiktokBeans);
                mAdapter.setData(data);
                runMainThread(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.notifyDataChanged();
                    }
                });
            }
        }).start();
    }

    /**
     * 切换任务到主线程执行
     *
     * @param runnable 执行的runnable
     */
    private void runMainThread(Runnable runnable) {
        EventRunner eventRunner = EventRunner.getMainEventRunner();
        EventHandler eventHandler = new EventHandler(eventRunner);
        eventHandler.postTask(runnable);
    }
}
